$(function() {
  var cubeSize = 20;
  var cubeCol = parseInt($('#canvas').width()) / cubeSize;
  var cubeRow = parseInt($('#canvas').height()) / cubeSize;
  var cubes = [];


  function Cube(el) {
    this.el = el;
  }

  function drawCube() {
    $('.canvas').each(function() {
      var rootEl = $(this);
      var prefix = rootEl.attr('id');
      for (var i = 0; i < cubeRow; i++) {
        var arrRow = [];
        for (var j = 0; j < cubeCol; j++) {
          var cubeEl = $('<div></div>').attr('id', prefix + "-cube-" + i + "-" + j).addClass('cube');
          cubeEl.css({
            width: cubeSize + 'px',
            height: cubeSize + 'px',
            left: j * cubeSize + 'px',
            top: i * cubeSize + 'px'
          });
          rootEl.append(cubeEl);
          arrRow.push(new Cube(cubeEl));
        }
        cubes.push(arrRow);
      }
    });

  }

  //第一中绘图方式
  $('#canvas').click(function(event) {
    var targetEl = event.target;
    $(targetEl).toggleClass('active');

  });

  //第二种绘图方式
  var isDrawing = false;
  var canvas2Offset = [0,0];
  function findCube(pageX, pageY) {
    var x = Math.floor(pageX / cubeSize);
    var y = Math.floor(pageY / cubeSize);
    return [x, y];
  }

  function triggleCube(selector, isActive) {
    console.log(selector);
    if (isActive) {
      $(selector).addClass('active');
    } else {
      $(selector).removeClass('active');
    }

  }
  $('#canvas2').on('mousedown', function(event) {
    isDrawing = true;
    canvas2Offset = $('#canvas2').offset();
    console.log('start draw...');
  }).on('mouseup', function(event) {
    isDrawing = false;
    console.log('end draw...');

  });
  $('#canvas2').on('mousemove', function(event) {
    if (!isDrawing) return;
    var cube = findCube(event.pageX-canvas2Offset.left, event.pageY-canvas2Offset.top);
    triggleCube('#canvas2-cube-' + cube[1] + "-" + cube[0], true);
  });


  $('.reset').click(function() {
    $('.canvas').html('');
    drawCube();
    //$('.cube.active').removeClass('active');
  });

  drawCube();
});